import React, { useMemo } from 'react';

/**
 * 格式化银行卡号
 * 将format中的格式化字符串转化为数组，动态拼接正则
 */
const BankCard = ({ cardNumber, format = 'xxxx-xxxx-xxxx-xxxx-xxx' }) => {
    const formattedCardNumber = useMemo(() => {
        const resolveRegExp = () => {
            const formatArray = format?.split('-') || [];
            let regex = '';
            let replaceStr = '';
            formatArray.forEach((item, index) => {
                regex += `(\\d{${item.length}})`;
                replaceStr += `$${index + 1} `;
            });
            return [new RegExp(regex), replaceStr.substring(0, replaceStr.length - 1)];
        };

        if (cardNumber) {
            const [regex, replaceStr] = resolveRegExp();
            return cardNumber.replace(regex, replaceStr);
        }

        return cardNumber;
    }, [cardNumber, format]);

    return <>{formattedCardNumber}</>;
};

export default BankCard;
